# -*- coding: utf-8 -*-
"""
Git processor.
"""
from processors.single_repository_processor import SingleRepositoryProcessor
import git
from datetime import datetime
from processors.changeinfo import ChangeInfo
from myutil import myutil
    
class LocalGitRepoProcessor(SingleRepositoryProcessor):
    """
    Processor for local git repository.
    """
    _repo = None
    
    def initialize(self):
        """
        Initializes the repository.
        """
        self._repo = git.Repo(self.location)

    def _gather_log_info(self):
        """
        Gather information from the repository about the changes.
        """
        for remote_branch in self._repo.remote().refs:
            commits = self._repo.iter_commits(remote_branch,max_count=100000)
            for i in commits:
                date = datetime.fromtimestamp(i.committed_date)
                parents = i.iter_parents()
                try:
                   parent = parents.next()
                   diff = i.tree.diff(parent) # Cheating.... only first parent is used :)
                   file_list = [ d.__str__().split('\n')[0] for d in diff]
                except StopIteration:
                   file_list = [ d.path for d in i.tree.traverse()]
                files = ", ".join(file_list)
                link = None
                if self.weburl is not None:
                    if self.flavor == "github":
                        link = self.weburl + "commit/" + i.hexsha
                    elif self.flavor == "googlecode":
                        link = self.weburl + "source/detail?r=" + i.hexsha
                email = myutil.get_mail(self.settings,i.author.email)
                change_info = ChangeInfo(i.hexsha, str(i.count()), \
                                i.author.name, email, date, \
                                files, i.message, link)
                self._append_change_info(change_info)

class PullableGitRepoProcessor(LocalGitRepoProcessor):
    """
    Git repository which is pullable.
    
    Every time we check it we also pull changes from the specified repository.
    """
    def pull(self):
        """
        Pulls changes from remote repository.
        """
        origin = self._repo.remotes.origin
        return str(origin.pull())      
